<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('iaMemberFieldSearch')) {

    function iaMemberFieldSearch($searchData = array())
    {
        $CI = & get_instance();
        $loading = $CI->lang->line('Loading');
        $_field_search_attribute = array(
            'textsearch' => array('name' => 'textsearch', 'id' => 'frm-textsearch',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_keyword'),
                'value' => set_value('textsearch', isset($searchData['textsearch']) ? $searchData['textsearch'] : '')
            ),
            'submit' => array('name' => 'btn-Search', 'class' => 'btn btn-primary', 'data-loading-text' => $loading,
                'id' => 'form-btnSearch', 'value' => $CI->lang->line('Search')),
            'reset' => array('name' => 'btn-Reset', 'class' => 'btn btn-primary', 'data-loading-text' => $loading,
                'id' => 'form-btnReset', 'value' => $CI->lang->line('Reset')),
        );

        return $_field_search_attribute;
    }

}

if (!function_exists('iaMemberFieldFilter')) {

    function iaMemberFieldFilter($filterData = array(), $filterSelected = 0)
    {
        $CI = & get_instance();
        $loading = $CI->lang->line('Loading');
        $_field_filter_attribute = array(
            'dropdown_filter' => array(
                'name' => 'function',
                'data' => $filterData,
                'selected' => $filterSelected,
                'extra' => "id='frm-ia-attribute-filter' class='span3'"
            ),
            'submit' => array('name' => 'btn-Filter', 'class' => 'btn btn-primary', 'data-loading-text' => $loading,
                'id' => 'form-btnSearch', 'value' => $CI->lang->line('Filter')),
            'reset' => array('name' => 'btn-Reset', 'class' => 'btn btn-primary', 'data-loading-text' => $loading,
                'id' => 'form-btnReset', 'value' => $CI->lang->line('Reset')),
        );

        return $_field_filter_attribute;
    }

}


//define field to generate form
if (!function_exists('iaMemberFieldForm')) {

    function iaMemberFieldForm($members = array())
    {
        global $CFG;
        $CI = & get_instance();
        if (count($members) && !empty($members)) {
            $firstname = $members->firstname;
            $lastname = $members->lastname;
            $member_name = $members->member_name;
            $updated = $members->updated;
            $avatar = $members->avatar;
            if ($avatar)
                $thumbAvatar = getThumbImage($CFG->item('folder_avatar') . $avatar, 50, 50);
            $type = $members->type;
            $ae = $members->ae;
            $function = $members->function;
            $manager = $members->manager;
            $qte = $members->qte;
            $active = $members->active;
        }
        $types = array(
            0 => 'User',
            1 => 'Manager',
            2 => 'IA'
        );
        $_field_form = array(
            'firstname' => array('name' => 'firstname', 'id' => 'frm-firstname',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('firstname', isset($firstname) ? $firstname : '')),
            'lastname' => array('name' => 'lastname', 'id' => 'frm-lastname',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('lastname', isset($lastname) ? $lastname : '')),
            'type' => array(
                'name' => 'type',
                'options' => $types,
                'selected' => isset($type) ? array($type) : array(),
            ),
            'avatar' => array('name' => 'avatar', 'id' => 'frm-avatar',
            ),
            'current_avatar' => array('value' => isset($thumbAvatar) ? $thumbAvatar : '',
                'width' => '50', 'height' => '50'
            ),
            'ae' => array('name' => 'ae', 'id' => 'frm-ae',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('ae', isset($ae) ? $ae : '')),
            'function' => array('name' => 'function', 'id' => 'frm-function',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('function', isset($function) ? $function : '')),
            'manager' => array('name' => 'manager', 'id' => 'frm-manager',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('manager', isset($manager) ? $manager : '')),
            'qte' => array('name' => 'qte', 'id' => 'frm-qte',
                'class' => 'span3', 'placeholder' => $CI->lang->line('Pls_enter_attribute'),
                'value' => set_value('qte', isset($qte) ? $qte : '')),
            'active'=>array('name'=>'active', 'id'=>'frm-active','checked'=>( ($active==1)?"checked":""  ),
                'class'=>'', 'value'=>$active),
            'submit' => array('class' => 'btn btn-primary', 'data-loading-text' => $CI->lang->line('Loading'),
                'id' => 'form-submit', 'value' => $CI->lang->line('Save')),
        );

        return $_field_form;
    }

}

//define field to validate form
if (!function_exists('iaMemberFieldValidate')) {

    function iaMemberFieldValidate()
    {
        $CI = & get_instance();
        $_field_validate = array(
            array(
                'field' => 'firstname',
                'label' => $CI->lang->line('Member_First_Name'),
                'rules' => 'trim|required|xss_clean'
            ),
            array(
                'field' => 'lastname',
                'label' => $CI->lang->line('Member_Last_Name'),
                'rules' => 'trim|required|xss_clean'
            ),
            array(
                'field' => 'ae',
                'label' => $CI->lang->line('Member_AE'),
                'rules' => 'trim|required|xss_clean'
            ),
            array(
                'field' => 'function',
                'label' => $CI->lang->line('Member_Function'),
                'rules' => 'trim|required|xss_clean'
            ),
            array(
                'field' => 'manager',
                'label' => $CI->lang->line('Member_Manager'),
                'rules' => 'trim|required|xss_clean'
            ),
            array(
                'field' => 'qte',
                'label' => $CI->lang->line('Member_QTE'),
                'rules' => 'trim|required|is_natural|xss_clean'
            ),
        );
        return $_field_validate;
    }

}

//get all user by manager
if (!function_exists('getMemberList')) {

    function getMemberList($currentManagerId = 0, $orderby = array())
    {
        $CI = & get_instance();
        $CI->load->model('manager/member_association_model', 'member_association_model');
        $CI->load->model('admin/manager_diagnosis_result_model', 'diagnosis_result_model');
        $CI->load->model('admin/manager_diagnosis_model', 'diagnosis_model');
        $memberList = array();
        if ($currentManagerId > 0) {
            $conditions = array(
                'owner_id' => $currentManagerId,
                'archived' => 0,
                'type' => 0,
                'active'=>1
            );
            $memberList = $CI->member_association_model->getAll($conditions);
        }

        $returnData = array();
        if (isset($memberList) && $memberList->num_rows() > 0) {

            foreach ($memberList->result() as $val) {
                $returnData[$val->id] = $val;
            }
            $arrUserIds = array(
                'field' => 'ia_id',
                'list' => implode(',',array_keys($returnData))
            );

            // list diagnosis of list user
            $listDiagnosisId = $CI->diagnosis_model->getListID($arrUserIds);
            if (isset($listDiagnosisId) && $listDiagnosisId->num_rows > 0) {
                foreach ($listDiagnosisId->result() as $val) {
                    $listUser[$val->ia_id] = $val->id;
                }
            }
            // get last update diagnosis of user
            $conditions = array (
                'field' => 'diagnosis_id',
                'list' => implode(',', array_values($listUser))
            );
            $diagnosisInfo = $CI->diagnosis_result_model
                ->getLastUpdate($conditions);
            foreach ($diagnosisInfo->result() as $info) {
                $diaData[$info->diagnosis_id] = $info;
            }

            foreach ($returnData as $uid => $userInfo) {
                $diaId = isset($listUser[$uid]) ? $listUser[$uid] : '';
                if (isset($diaData[$diaId])) {
                   $lastUpdate = $diaData[$diaId]->updated;
                } else {
                    $lastUpdate = $returnData[$uid]->created;
                }
                $userInfo->last_updated = $lastUpdate;
                $returnData[$uid]->last_updated = $lastUpdate;
            }
        }
        if ($orderby['m.updated'] == 'DESC') {
            usort($returnData, 'cmpTimeDesc');
        } else {
            usort($returnData, 'cmpTimeAsc');
        }
        $response = array();
        foreach ($returnData as $val) {
            $response[$val->id] = $val;
        }
        return $response;
    }

}

function cmpTimeAsc($firstTime, $lastTime)
{
    if (strtotime($firstTime->last_updated) == strtotime($lastTime->last_updated)) {
        return 0;
    }
    return (strtotime($firstTime->last_updated) < strtotime($lastTime->last_updated)) ? -1 : 1;
}

function cmpTimeDesc($firstTime, $lastTime)
{
    if (strtotime($firstTime->last_updated) == strtotime($lastTime->last_updated)) {
        return 0;
    }
    return (strtotime($firstTime->last_updated) > strtotime($lastTime->last_updated)) ? -1 : 1;
}


//get all user by ia
if (!function_exists('getMember')) {

    function getMember($currentIAId = 0, $orderby = array())
    {
//                echo "<pre>";
//        print_r($orderby);
//        die();
        $CI = & get_instance();
        $CI->load->model('ia/member_association_model', 'ia_association_model');
        $CI->load->model('admin/ia_diagnosis_model', 'ia_diagnosis_model');
        $memberList = array();
        if ($currentIAId > 0) {
            $conditions = array(
                'owner_id' => $currentIAId,
                'archived' => 0,
                'active'=>1
            );
            $memberList = $CI->ia_association_model->getAll($conditions);
        }
        // get ia diagnosis
        $condition = array(
            'c.owner_id' => $currentIAId,
        );

        $members = $CI->ia_diagnosis_model->getAll($condition, NULL, NULL, NULL, $orderby);
        $diagnosis = array();
        if (isset($members) && $members->num_rows() > 0) {
            foreach ($members->result() as $k => $val) {
                if(!isset($diagnosis[$val->member_id])){
                    $diagnosis[$val->member_id] = $val;
                } else {
                    // get last diagnosis
                    if($diagnosis[$val->member_id]->updated <= $val->updated){
                        $diagnosis[$val->member_id] = $val;
                    }
                }
            }
        }

        $returnData = array();
        if (isset($memberList) && $memberList->num_rows() > 0) {
            foreach ($memberList->result() as $k => $val) {
                $val->diagnosis = isset($diagnosis[$val->user_id]) ? $diagnosis[$val->user_id] : array();
                $returnData[$val->id] = $val;
            }
        }

        $tempOrder = array();
        foreach ($diagnosis as $key => $dian) {
            if (isset($returnData[$key])) {
                $tempOrder[$key] = $returnData[$key];
            }
            unset($returnData[$key]);
        }
        //echo "<pre>";
        //var_dump($members->result());die;
        if (isset($orderby['c.step']) && $orderby['c.step'] == 'DESC') {
            $returnData = $tempOrder + $returnData;
        } else {
            $returnData = $returnData + $tempOrder;
        }


        return $returnData;
    }

}

// get member list to add member
if (!function_exists('memberList')) {

    function memberList($condition, $mid = 0, $or_condition = array())
    {

        $CI = & get_instance();
        $CI->load->model('admin/member_model', 'member_model');
        $CI->load->model('manager/member_association_model', 'assoc_model');

        // get all user managed by $mid, Who not archived
        $currentAssocCondition = array(
            'owner_id' => $mid,
            'archived' => 0
        );
        $curentManaged = $CI->assoc_model->getAll($currentAssocCondition);
        $curentAssocListId = array();
        if (isset($curentManaged) && $curentManaged->num_rows() > 0) {
            foreach ($curentManaged->result() as $i => $item) {
                $curentAssocListId[$item->user_id] = $item->user_id;
            }
        }

        $assocListId = array();
        // case manager
        if($condition['ismanager'] == 1) {
            // ignore all userid managed by other managers

            $listIgnoreUser =  $CI->assoc_model->getIgnoreUserList($mid);
            $otherAssocListId = array();
            if ($listIgnoreUser->num_rows() > 0) {
                foreach ($listIgnoreUser->result() as $item) {
                    $otherAssocListId[$item->user_id] = $item->user_id;
                }
            }
            $mergeList = array_merge($curentAssocListId, $otherAssocListId);
            foreach ($mergeList as $k => $val) {
                $assocListId[$val] = $val;
            }

        }
        // case IA
        if (!count($assocListId)) {
            $assocListId = $curentAssocListId;
        }
        unset($condition['ismanager']);
        $member = $CI->member_model->getAll($condition, '', array(), array(), array(), '', $or_condition);

        $listMember = array();
        if (isset($member) && $member->num_rows() > 0) {
            foreach ($member->result() as $k => $val) {
                if (!in_array($val->id, $assocListId)) {
                    $listMember[] = array(
                        'user_id' => $val->id,
                        'user_name' => ucfirst(strtolower($val->firstname)) . ' ' . ucfirst(strtolower($val->lastname))
                    );
                }
            }
        }
        return $listMember;
    }

}

// add user
if (!function_exists('addUser')) {

    function addUser($mid, $uid, $redirectLink)
    {
        $CI = & get_instance();
        $CI->load->model('manager/member_association_model', 'member_association_model');

        // check user and manager
        $checked = $CI->member_association_model->checkIAAssoc($mid, $uid);
        // no user and manager
        // update exists user has been archived to active
        if ($checked) {
            $conditions = array(
                'owner_id' => $mid,
                'user_id' => $uid
            );
            // update
            $updateData = array(
                'archived' => 0
            );
            $returnInfo = $CI->member_association_model->updateIAAssoc($conditions, $updateData);

        } else {

           //$isManager select $mid from sm_member where type = 1
            $isManager = isManager($mid);

            if ($isManager)
            {
                if (sizeof($checkInfo) && $checkInfo->num_rows() > 0) {

                    $returnData = array(
                        'url' => '',
                        'status' => '404',
                        'message' => 'This user was managed by other manager!'
                    );
                    return $returnData;
                } else {
                    // add user to manager
                    $addData = array(
                        'owner_id' => $mid,
                        'user_id' => $uid
                    );
                    $returnInfo = $CI->member_association_model->addIAAssoc($addData);
                }
            } else {
                // add user to manager
                $addData = array(
                    'owner_id' => $mid,
                    'user_id' => $uid
                );
                $returnInfo = $CI->member_association_model->addIAAssoc($addData);
            }
        }

        $returnData = array(
            'url' => $redirectLink,
            'status' => $returnInfo,
            'message' => 'success'
        );

        return $returnData;
    }

}

if(!function_exists('isHaveManager')){
    function isHaveManager($user) {
        $CI = & get_instance();
        $CI->load->model('manager/member_association_model', 'assoc_model');
//        $where = array(
//            "user_id"=>$user['user_id']
//        );
//        //$data = $CI->assoc_model->getAll($where);
//        $data = $CI->assoc_model->db->where($where);
        $CI->assoc_model->db->from('sm_user_association');
        $CI->assoc_model->db->select("*");

        $result = $CI->assoc_model->db->get();
        return $result->num_rows();
    }
}

if(!function_exists('isManager')){
    function isManager($mid){
        $CI = & get_instance();
        $CI->load->model('admin/member_model', 'member_model');
        $where = array(
            "id"=>$mid,
            "type"=>1
        );
        //$data = $CI->assoc_model->getAll($where);
        $data = $CI->member_model->db->where($where);
        $CI->member_model->db->from('sm_member');
        $CI->member_model->db->select("*");
        $result = $CI->member_model->db->get();
        if(isset($result) && $result->num_rows()>0)
            return true;
        return false;
    }
}